package org.kinglone.weixin.controller;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.kinglone.weixin.kit.BasicKit;
import org.kinglone.weixin.kit.SecurityKit;
import org.kinglone.weixin.kit.WeixinMessageKit;
import org.kinglone.weixin.web.servlet.WeixinContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class WeixinBasicController {

	/**
	 * get请求验证消息的确来自微信服务器
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping(value="/msg",method=RequestMethod.GET)
	public void handlerGet(HttpServletRequest req,HttpServletResponse resp) throws IOException {
		
		String signature = req.getParameter("signature");//微信加密签名
		String timestamp = req.getParameter("timestamp");//时间戳
		String nonce = req.getParameter("nonce");//随机数
		String echostr = req.getParameter("echostr");//	随机字符串		
		System.out.println("---signature:"+signature+"---timestamp:"+timestamp+"---nonce:"+nonce+"---echostr:"+echostr);

		//1)将token、timestamp、nonce三个参数进行字典序排序
		String[] arr = {WeixinContext.getInstance().getToken(),timestamp,nonce};
		Arrays.sort(arr);//排序
		StringBuffer sb = new StringBuffer();
		for(String a:arr) {
			sb.append(a);
		}		
		//2）将三个参数字符串拼接成一个字符串进行sha1加密
		String sha1Msg = SecurityKit.sha1(sb.toString());
		System.out.println("-----:sha1Msg:"+sha1Msg);//-----:sha1Msg:f106ef7ef736295dec2a709e794038b83711d20d
		if(signature.equals(sha1Msg)) {
			resp.getWriter().println(echostr);
		}
	}
	
	/**
	 * post请求处理消息
	 * @param req
	 * @param resp
	 */
	@RequestMapping(value="/msg",method=RequestMethod.POST)
	public void handlerPost(HttpServletRequest req,HttpServletResponse resp) throws IOException{
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/xml;charset=utf-8");
		resp.setCharacterEncoding("utf-8");
		String rel = WeixinMessageKit.handlerReceiveMsg(req);
		System.out.println("-------------rel:"+rel);
		if(!BasicKit.isEmpty(rel)){
			resp.getWriter().write(rel);
		}
		
	}
	
}
